package pers.mihao.quickstream.start.chart;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
@Controller
public class ChartController {

    @Resource
    DataSource dataSource;

    @GetMapping("helloView")
    public ModelAndView hello() {
        return new ModelAndView("hello");
    }

    /**
     * 任务执行报表
     *
     * @param model
     * @return
     */
    @GetMapping("/testTask")
    public String showChart(Model model) {
        List<Long> temperatures = getData("select " +
                "TIMESTAMPDIFF(SECOND, t.next_invoke_time, t.last_invoke_time) " +
                "from tb_timeout_task t where status = 'STOP' order by next_invoke_time");

        List<String> labels = new ArrayList<>(temperatures.size());
        for (int i = 0; i < temperatures.size(); i++) {
            labels.add(i, "" + i);
        }

        // 将数据传递到模型
        model.addAttribute("temperatures", temperatures);
        model.addAttribute("charName", "执行时间延迟");
        model.addAttribute("labelName", "延迟(s)");
        model.addAttribute("labels", labels);
        return "chart-line";
    }

    private List<Long> getData(String sql) {
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            List<Long> list = new ArrayList<>();
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                long aLong = resultSet.getLong(1);
                list.add(aLong);
            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
